﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Budget.DataAccess.Repository;

namespace Budget.DataAccess.Services
{
	public class CategoryDataService : ICategoryDataService
	{
		private IRepository<Category> repo;

		public CategoryDataService( IRepository<Category> repository )
		{
			repo = repository;
		}

		public IList<Category> GetAll()
		{
			IList<Category> categories;

			using ( repo )
			{
				categories = ( from c in repo.Query()
							   orderby c.CategoryName
							   select c ).ToList();
			}

			return categories;
		}

		public Category GetById( int categoryId )
		{
			Category category;

			using ( repo )
			{
				category = ( from c in repo.Query()
							 where c.CategoryId == categoryId
							 select c ).FirstOrDefault();
			}

			return category;
		}

		public void Save( Category category )
		{
			using ( repo )
			{
				if ( category.CategoryId == 0 )
				{
					repo.Add( category );
				}
				else
				{
					repo.Attach( category );
				}

				repo.SubmitChanges();
			}
		}
	}
}
